package com.ushine.web.component.authority.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import com.ushine.web.base.model.base.DataFilterMetaDataBO;
import com.ushine.web.component.authority.config.DataFilterThreadLocal;
import com.ushine.web.component.authority.service.TemplateManagerServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.HexValue;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: yls
 * @Date 2022/2/9 11:33
 * @Description: 数据权限：查询权限处理器
 * @Version 1.0
 **/
@Slf4j
@Component
public class QueryDataPermissionHandler implements DataPermissionHandler {

    @Resource
    private TemplateManagerServiceImpl templateManagerService;

    @SneakyThrows
    @Override
    public Expression getSqlSegment(Expression where, String mappedStatementId) {
        // 获取权限过滤相关的信息
        DataFilterMetaDataBO dataFilterMetaDataBO = DataFilterThreadLocal.getDataFilter();
        // 不需要权限过滤
        if (dataFilterMetaDataBO == null) {
            log.info("*****************不需要进行数据行级拦截：" + where);
            return where;
        }
        log.error(dataFilterMetaDataBO.toString());

        if (where == null) {
            where = new HexValue("1=1");
        }

        where = templateManagerService.getDataQueryExpression(where, dataFilterMetaDataBO);
        log.error("数据隔离级别：{}<=>{}", dataFilterMetaDataBO.getFilterType(), dataFilterMetaDataBO.getFilterType());
        return where;
    }


}
